const Router = require("koa-router");
const mysql = require("mysql2/promise");
const bodyParser = require("koa-bodyparser");

const router = new Router();

router.use(bodyParser());
// 定义数据库连接配置
const dbConfig = {
  host: "localhost",
  user: "root",
  password: "root",
  database: "student",
};
router.post("/register", async (ctx) => {
  const newUser = ctx.request.body;

  if (!newUser.name || !newUser.age) {
    ctx.status = 400;
    ctx.body = { error: "姓名和年龄不能为空lala" };
    return;
  }

  newUser.id = users.length + 1;
  users.push(newUser);

  try {
    const connection = await mysql.createConnection(dbConfig);

    await connection.execute(
      "INSERT INTO stu_user (user_name, user_age, user_id) VALUES (?, ?, ?)",
      [newUser.name, newUser.age, newUser.id]
    );

    await connection.end();
  } catch (error) {
    console.error(error);
    ctx.status = 500;
    ctx.body = { error: "数据库操作失败" };
    return;
  }

  ctx.status = 201;
  ctx.body = {
    newUser,
    code: 200,
    message: "新增成功",
  };
});

router.post("/login", async (ctx) => {
  const { UserName, Password } = ctx.request.body;

  try {
    const connection = await mysql.createConnection(dbConfig);

    const [rows] = await connection.execute(
      "SELECT * FROM users WHERE username = ?",
      [UserName]
    );

    await connection.end();

    if (rows.length > 0) {
      const user = rows[0];

      if (Password == user.password) {
        ctx.body = {
          message: "登录成功",
          token: "myToken-xxx",
          code: 200,
          permissions: ["admin"],
          id: user.id,
          name: user.username,
          neckname: user.neckname,
        };
      } else {
        ctx.status = 401;
        ctx.body = { error: "用户名或密码错误" };
      }
    } else {
      ctx.status = 401;
      ctx.body = { error: "用户名或密码错误" };
    }
  } catch (error) {
    console.error(error);
    ctx.status = 500;
    ctx.body = { code: 500, error: "内部服务器错误" };
  }
});

module.exports = router;
